package id.co.shuba.spamobile.task;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.Encryptor;
import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.activities.DownloadActivity;
import id.co.shuba.spamobile.activities.LoginActivity;
import id.co.shuba.spamobile.activities.MainActivity;
import id.co.shuba.spamobile.activities.UpdateActivity;
import id.co.shuba.spamobile.data.AreaDB;
import id.co.shuba.spamobile.data.BaseDB;
import id.co.shuba.spamobile.model.UserInfo;
import id.co.shuba.spamobile.services.WebServiceHelper;
import id.co.shuba.spamobile.util.Base64;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Camera.Size;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.sax.StartElementListener;
import android.view.ContextThemeWrapper;
import android.widget.Toast;

public class CheckForUpdateTask extends AsyncTask<String, Integer, AsyncTaskResult<Void>> {	
	ProgressDialog _dialog;
	WebServiceHelper _ws;
	UserInfo _user;
	String _imei;
	String _version;
	String _size;
	long _checksum;
	boolean _forceUpdate;	
	
	private OnCheckingFinished _callback;
	
	public void setOnCheckingFinished(OnCheckingFinished callback) {
		_callback = callback;
	}	
	
	public void setDialog(ProgressDialog dialog) {
		_dialog = dialog;
		if (getStatus() == Status.RUNNING)
			_dialog.show();
	}
	
	public CheckForUpdateTask(WebServiceHelper ws, UserInfo user, String imei, boolean forceUpdate, ProgressDialog dialog) {
		_ws = ws;
		_user = user;
		_imei = imei;		
		_forceUpdate = forceUpdate;		
		_dialog = dialog;
	}	
	
	@Override
	protected void onPreExecute() {	
		super.onPreExecute();	
		_dialog.show();
	}
	
	@Override
	protected AsyncTaskResult<Void> doInBackground(String... params) {
		try {			
			Encryptor enc = new Encryptor(
					Encryptor.ENC_AES,
					Encryptor.ENC_AES, App.createCompleteKey(_user.getEncryptionKey()), App.IV);
			String pwd = enc.decryptText(_user.getPassword());	
			
			Map<String, Object> properties = new HashMap<String, Object>();
			properties.put("version", App.getAppVersion(_ws.getContext()));
			properties.put("nip", _user.getNip());
			properties.put("password", pwd);
			properties.put("imei", _imei);
			properties.put("token", _user.getToken());
			properties.put("unit", _user.getUnitCode());
						
			String result = _ws.Call("CheckForUpdateByUnit", properties).toString();			
									
			String strJSON = new String(Base64.decode(result, Base64.GZIP)); 						
			
			JSONObject res = new JSONObject(strJSON);
			String error = res.getString("error");
			if (error.length() > 0 && !error.equals("null"))
				throw new Exception(error);
				
			JSONObject jsonObj = res.getJSONObject("result");					
			_version = jsonObj.getString("version");
			_size = jsonObj.getString("size");
			_checksum = jsonObj.getLong("checksum");
			
			return new AsyncTaskResult<Void>((Void) null);
		} catch (Exception e) {			
			return new AsyncTaskResult<Void>(e);
		}			
	}
	
	@Override
	protected void onPostExecute(AsyncTaskResult<Void> result) {	
		_dialog.dismiss();
		
		if (result.getError() != null) {
			Toast.makeText(_dialog.getContext(),
					result.getError().getMessage(), Toast.LENGTH_LONG).show();
			
			if ("Application is up to date".equals(result.getError().getMessage()))
				if (_callback != null)
					_callback.updateNotFound();
			
			return;
		}				
			
		if (_callback != null) {					
			_callback.updateFound(_version, _size, _checksum);
		}
	}	
		
}